package com.central.apps.handler;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.util.BLuntil;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

@Log4j2
@Component
public class DefectreportHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;

    /**
     * 缺陷提报单设置节点自定义审批人
     *
     * @param app
     * @param id
     * @param flowNode
     * @param vars
     * @return
     * @throws Exception
     */
    public String addFlowCandidate(String app, Long id, FlowNode flowNode, Map<String, Object> vars) throws Exception {
        //定义一个存放人员的字符串
        String executer = null;
        //查询到单据的deptcode，检修班长，检修工，验收人员
        List<Map<String, Object>> defectreport = handlerService.findBySql("select deptcode,monitor1,monitor2,accetpperson,branchleader from bl_defectreport where id="+id);
        //拿到deptcode
        String deptcode = MapUtil.getStr(defectreport.get(0), "deptcode");
        String monitor1=MapUtils.getString(defectreport.get(0),"monitor1");//检修班长
        String monitor2=MapUtils.getString(defectreport.get(0),"monitor2");//检修工
        String accetpperson=MapUtils.getString(defectreport.get(0),"accetpperson");//验收人员
        String branchleader=MapUtils.getString(defectreport.get(0),"branchleader");//分厂负责人

        //分厂负责人
        if (flowNode.getId().equals("fcfzr")) {
            if (branchleader!=null&&!branchleader.equals("")){
                executer=branchleader;
            }
        }
        //检修班长 人员节点  获取到页面上的班组长账号
        if (flowNode.getId().equals("jxbz")) {
            if (monitor1!=null&&!monitor1.equals("")){
                executer=monitor1;
            }
        }
        //检修工人员节点
        else if (flowNode.getId().equals("jxg")){
            if (monitor2!=null&&!monitor2.equals("")){
                executer=monitor2;
            }
        }
        //验收人员节点
        else if (flowNode.getId().equals("ysry")){
            if (accetpperson!=null&&!accetpperson.equals("")){
                executer=accetpperson;
            }
        }
        //点检员节点
        else if (flowNode.getId().equals("djy")){
            List<Map<String, Object>> persons = handlerService.findBySql("select u.username from bl_person p left join sys_user u on p.personid = u.worknumber where LEFT(p.deptcode,6)= LEFT('"+deptcode+"',6)" +
                    " and position like '%点检员%' ");
            if (CollectionUtils.isNotEmpty(persons)) {
                //人员以逗号隔开
                StringJoiner sj = new StringJoiner(",", "", "");
                for (Map<String, Object> username : persons) {
                    sj.add(MapUtils.getString(username, "username"));
                }
                executer = sj.toString();

            }
        }
        return executer;
    }


//    @Override
//    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
//        if ("defectreportApp".equals(app)) {//判断是否为缺陷提报单
//            if ("tbrtj".equals(flowNode.getId())) {//提报人提交节点
//                List<Map<String, Object>> list = handlerService.findBySql(
//                        "select type from bl_defectreport where id="+id);
//                String type = MapUtils.getString(list.get(0), "type");//获取到缺陷处理类型
//                if ("整改".equals(type)) {
//                    return  "整改类型的缺陷提报单不可提交流程";
//                }
//            }
//        }
//        return super.beforeExcuteFlow(app, id, flowNode, op);
//    }
@Override
public Object operate(String app, String type, Map<String, Object> params) throws Exception {
    //归属单位弹出框
    if ("getGroup".equals(type)) {
        String deptcode = MapUtils.getString(params, "deptcode");
        String groupnum = BLuntil.getParameter(params, "groupnum");
        String description = BLuntil.getParameter(params, "description");
        String depInfo = BLuntil.getParameter(params, "depInfo");

        if(deptcode != null && !"".equalsIgnoreCase(deptcode)){
            if(depInfo!=null && !"".equals(depInfo)){
                String sql="SELECT  groupnum,description  from bl_workgroup  where     LEFT(deptcode,6)=  LEFT('"+deptcode+"',6) and grouptype=1    and  groupnum   like '%"+depInfo+"%'  or  description  like   '%"+depInfo+"%'";
                return BLuntil.toPage(params, handlerService, sql);
            }else{
                String sql="SELECT  groupnum,description  from bl_workgroup  where     LEFT(deptcode,6)=  LEFT('"+deptcode+"',6) and grouptype=1    and  groupnum   like '%"+groupnum+"%'  and  description  like   '%"+description+"%'";
                return BLuntil.toPage(params, handlerService, sql);
            }

        }
    }
    //获取分厂设备科长或车间主任
    if ("getBranchleader".equals(type)) {
        String deptcode = MapUtils.getString(params, "deptcode");
        String personid = BLuntil.getParameter(params, "personid");
        String name = BLuntil.getParameter(params, "name");
        if(deptcode != null && !"".equalsIgnoreCase(deptcode)){
            String sql=" select p.personid,p.name from bl_person p left join sys_user u on p.personid = u.worknumber where LEFT(p.deptcode,6)= LEFT('"+deptcode+"',6)"+
                    "  and (p.position like '%设备科长%'  or p.position like '%车间主任%') and p.personid  like  '%"+personid+"%'  and  p.name  like   '%"+name+"%' ";
            return BLuntil.toPage(params, handlerService, sql);
        }
    }
    //获取班组人员选择框
    if ("getWorkshopperson".equals(type)) {
        String team1 = MapUtils.getString(params, "team1");//获取班组编号
        String personid = BLuntil.getParameter(params, "personid");//高级查询人员编号
        String name = BLuntil.getParameter(params, "name");//高级查询人员姓名
        String depInfo = BLuntil.getParameter(params, "depInfo");//手机app高级查询参数
        if(team1 != null && !"".equalsIgnoreCase(team1)){
            String sql="SELECT  personid,name from bl_person " +
                    "  where   workgroup='"+team1+"' and personid  like  '%"+personid+"%'  and  name  like   '%"+name+"%' ";
            return BLuntil.toPage(params, handlerService, sql);
        }
    }
    return super.operate(app, type, params);
}
     //缺陷提报单检修工审批后自动生成工单
    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if(flowNode.getId().equals("jxg")){
            boolean flag = op.isFlag();//判断是否审核通过
            //审核通过的情况
            if(flag) {
                String WONUM = handlerService.findBizNum("workorderApp", "bl_workorder");//生成工单编号
                Map<String, Object> map = handlerService.findMainById(app, id);//获取缺陷提报单主对象
                String reportnum= MapUtils.getString(map,"reportnum");//获取缺陷提报单的编号
                String isnoworker= MapUtils.getString(map,"isnoworker");//获取缺陷提报单的是否生成工单标识
                //获取到车间检修计划中的所有信息
                List<Map<String, Object>> planTaskList1 = handlerService.findBySql(" select a.*, user.nickname,user.id userid from bl_defectreport a " +
                        "left join sys_user user on  a.monitor2=user.username " +
                        "where a.reportnum='"+reportnum+"'");
                if(planTaskList1!=null && planTaskList1.size()>0){
                    String userid=MapUtils.getString(planTaskList1.get(0),"userid");//获取到检修计划行信息中的检修负责人
                    String nickname=MapUtils.getString(planTaskList1.get(0),"nickname");//获取到检修计划行信息中的检修负责人名字
                    if(isnoworker.equals("是")){//如果标识为“是”就生成工单并启动工单流程
                        //生成工单并将缺陷提报单的部分字段带入到工单中
                        handlerService.findBySql(" insert into bl_workorder (WONUM,DESCRIPTION,type,UDWOTYPE,REPORTNUM,reportnumdesc,status,area,deptcode,ASSETNUM,LOCATION,createuser,createtime,maintenanceprincipal,acceptanceperson,maintenancesection,approveornot) " +
                                " ( select '"+WONUM+"' as WONUM, ifnull(reportname,''),'基本工单','缺陷工单',ifnull(reportnum,''),ifnull(reportname,''),'草稿',ifnull(area,''),ifnull(deptcode,''),ifnull(assetnum,''),ifnull(location,''),'"+userid+"' as createuser,now() as createtime,ifnull(monitor2,'')," +
                                " ifnull(accetpperson,''),ifnull(team1,''),'否' from bl_defectreport where id='"+id+"')");
                        //生成工单后将工单编号更新到缺陷提报单中
                        handlerService.findBySql(" update bl_defectreport set wonum='"+WONUM+"' where  id='"+id+"'");
                        //启动工单的流程
                        List<Map<String, Object>> reportlist = handlerService.findBySql
                                ("select id,maintenanceprincipal from bl_workorder where WONUM='"+WONUM+"'");//获取工单的id
                        Long reportID = MapUtils.getLong(reportlist.get(0), "id");
                        String maintenanceprincipal = MapUtils.getString(reportlist.get(0), "maintenanceprincipal");
                        FlowOpinion flowOpinion = new FlowOpinion();
                        flowOpinion.setOpId(maintenanceprincipal);
                        flowOpinion.setOpName(nickname);
                        try {
                            handlerService.forcibleStart("workorderApp", reportID, flowOpinion);
                        } catch (Exception e) {
                        }
                    }
                }

            }

        }
    }
}
